package com.whu.exp1jsp.controller;

import com.sun.xml.internal.bind.v2.TODO;
import com.whu.exp1jsp.dao.UserDAO;
import com.whu.exp1jsp.pojo.UserSt;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.sql.SQLException;

@WebServlet(name = "alterPasswordServlet", value = "/alter-password-servlet")
public class AlterPasswordServlet extends HttpServlet {

    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // 获取表单参数
        String account = request.getParameter("account");
        String newPassword = request.getParameter("newPassword");
        String confirmPassword = request.getParameter("confirmPassword");
        String verificationCode = request.getParameter("verificationCode");
        // 目前将验证码当作密码
        // TODO: 验证码验证

        if (!newPassword.equals(confirmPassword)) {
            request.setAttribute("errorMessage", "两次输入的密码不一致");
            request.getRequestDispatcher("login.jsp").forward(request, response);
        }

        UserDAO userDAO = new UserDAO();
        UserSt userSt = null;
        try {
            userSt = userDAO.selectUserByPhoneNum(account);
        }catch (SQLException e){
            request.setAttribute("error", e.getMessage());
            request.getRequestDispatcher("error.jsp").forward(request, response);
        }

        if (userSt != null && userSt.getUserPassword().equals(verificationCode)) {
            userSt.setUserPassword(newPassword);
            try {
                userDAO.updateUser(userSt);
            } catch (SQLException e) {
                request.setAttribute("error", e.getMessage());
                request.getRequestDispatcher("error.jsp").forward(request, response);
            }
            // 修改密码成功，返回登录页面
            request.setAttribute("successMessage", "修改密码成功");
            request.getRequestDispatcher("login.jsp").forward(request, response);

        } else {
            // 登录失败，返回登录页面并显示错误信息
            request.setAttribute("errorMessage", "验证码错误！");
            request.getRequestDispatcher("login.jsp").forward(request, response);
        }

    }

}
